<template>
  <div class="song-list">
    <div class="header">
      <h2>歌曲列表</h2>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索歌曲、歌手"
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch" />
        </template>
      </el-input>
    </div>

    <el-table
      :data="songs"
      v-loading="loading"
      stripe
      style="width: 100%"
      @row-click="playSong"
      class="song-table"
    >
      <el-table-column label="图片" width="100">
        <template #default="scope">
          <div class="image-container">
            <el-image
              :src="scope.row.songPic || defaultImage"
              class="song-image"
              fit="cover"
              @error="handleImageError"
              lazy
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="songName" label="歌曲名" min-width="200">
        <template #default="scope">
          <div class="text-ellipsis song-name">{{ scope.row.songName }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="singerName" label="歌手" min-width="150">
        <template #default="scope">
          <div class="text-ellipsis singer">{{ scope.row.singerName }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="songAlbum" label="专辑" min-width="200">
        <template #default="scope">
          <div class="text-ellipsis album">{{ scope.row.songAlbum }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="duration" label="时长" width="100" align="center">
        <template #default="scope">
          {{ formatDuration(scope.row.duration) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" icon="VideoPlay" circle @click.stop="playSong(scope.row)" />
          <el-button icon="Plus" circle @click.stop="addToPlaylist(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper, ->, total"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>


<script>
import { ref, reactive, onMounted } from 'vue'
import { usePlayerStore } from '@/../../music-manage/src/store/player'
import { getSongList, searchSongs } from '@/services/song'
import { ElMessage } from 'element-plus'
import songDefaultImage from '@/assets/img/song-default.png'

export default {
  name: 'SongList',
  setup() {
    const playerStore = usePlayerStore()
    const defaultImage = songDefaultImage

    // 数据状态
    const songs = ref([])
    const loading = ref(false)
    const searchKeyword = ref('')

    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 获取歌曲列表
    const fetchSongs = async () => {
      try {
        loading.value = true
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }

        const response = await getSongList(params)
        if (response.code === '1') {
          songs.value = response.data.list || response.data.records || []
          total.value = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取歌曲列表失败')
        }
      } catch (error) {
        console.error('获取歌曲列表失败',error)
        ElMessage.error('获取歌曲列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

    // 搜索歌曲
    const handleSearch = async () => {
      if (!searchKeyword.value.trim()) {
        // 如果搜索关键词为空，获取全部歌曲
        await fetchSongs()
        return
      }

      try {
        loading.value = true
        const response = await searchSongs(searchKeyword.value)
        if (response.code === '1') {
          songs.value = response.data.list || response.data.records || []
          total.value = response.data.total || 0
        } else {
          ElMessage.error(response.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索失败', error)
        ElMessage.error('搜索失败: ' + ( error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

    // 播放歌曲
    const playSong = (song) => {
      playerStore.setCurrentSong(song)
      playerStore.togglePlay() // 开始播放
      ElMessage.success(`正在播放: ${song.name}`)
    }

    // 添加到播放列表
    const addToPlaylist = (song) => {
      playerStore.setPlaylist([...playerStore.playlist, song])
      ElMessage.success(`已添加到播放列表: ${song.name}`)
    }

    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }

    // 处理分页变化
    const handlePageChange = (page) => {
      currentPage.value = page
      if (searchKeyword.value.trim()) {
        handleSearch()
      } else {
        fetchSongs()
      }
    }

    const handleImageError = (event) => {
      event.target.src = defaultImage
    }

    // 初始化加载
    onMounted(() => {
      fetchSongs()
    })

    return {
      songs,
      loading,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      playSong,
      addToPlaylist,
      formatDuration,
      handleSearch,
      handlePageChange,
      handleImageError
    }
  }
}
</script>

<style scoped>
.song-list {
  padding: 20px;
  padding-bottom: 100px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.song-table :deep(.el-table__row) {
  height: 80px;
}

.image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
}

.song-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 24px;
}

.song-name {
  font-weight: 500;
  cursor: pointer;
}

.song-name:hover {
  color: #409eff;
}

.singer,
.album {
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>

